<template>
  <fieldTree
    :field-items="fieldItems"
    :default-expanded-keys="defaultExpandedKeys"
    :allow-drop="allowDrop"
    :allow-drag="allowDrag"
    :draggable="!isLoading"
    :extent-select="{
      key: 'linkInvoiceType',
      list: invoiceTypesList,
      placeholder:'请选择开票发票类型',
      auth: showSelect
    }"
    checkbox-required
    required-text="纳税人信息必填"
    @node-drop="handleDrop"
    @getData="getData" />
</template>

<script>
import fieldTree from '@/components/SettingPage/fieldTree';
import { ourTitleSort } from '@/api/setting';
import ElMessage from '@/utils/message';

export default {
  components: { fieldTree },
  props: {
    fieldItems: {
      type: Array,
      default: () => {
        return [];
      }
    },
    defaultExpandedKeys: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      isLoading: false
    };
  },
  computed: {
    invoiceTypesList() {
      const types = this.fieldItems.find(i => i.name === '发票类型');

      return types ? types.item : [];
    }
  },
  methods: {
    getData(respetPid) {
      this.$emit('getData', respetPid);
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      const orderPlatform = this.fieldItems.find(i => i.name === '我方抬头');
      if (orderPlatform && orderPlatform.item) {
        const params = {
          sortArr: orderPlatform.item
        };
        let respetPid = [];
        if (dropNode.parent && dropNode.parent.data && dropNode.parent.data.pid) {
          respetPid = [dropNode.parent.data.pid];
        }
        this.isLoading = true;
        ourTitleSort(params).then((res) => {
          this.getData(respetPid);
          this.isLoading = false;
          if (res.code) {
            ElMessage.success('排序成功');
          } else {
            ElMessage.error(res.message);
          }
        }).catch(() => {
          this.getData(respetPid);
          this.isLoading = false;
        });
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      if (type === 'inner') return false;
      const parent = dropNode.parent || null;
      let canDrag = false;
      if (parent && parent instanceof Object && parent.data.name === '我方抬头') {
        canDrag = true;
      }
      return dropNode.isLeaf && canDrag;
    },
    allowDrag(draggingNode) {
      const parent = draggingNode.parent || null;
      let canDrag = false;
      // 我方抬头的子节点才能拖拽
      if (parent && parent instanceof Object && parent.data.name === '我方抬头') {
        canDrag = true;
      }
      return draggingNode.isLeaf && canDrag;
    },
    showSelect(node, data) {
      if (node.level === 2 && node.parent && node.parent.data.name === '我方抬头') {
        return true;
      }
      return false;
    }
  }
};
</script>
